﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Common
{
	/// <summary>
    /// 脚本单例类
    /// </summary>
	public class MonoSingleton<T> : MonoBehaviour where T:MonoSingleton<T>
    {
        //public static T Instance { get; private set; }

        //按需加载
        private static T instance;
        public static T Instance
        {
            get
            {
                if (instance == null)
                {
                    //instance = this as T;//在静态方法中无法调用实例
                    instance = FindObjectOfType<T>();//在场景中查找该类型实例
                    if (instance == null)
                    {
                        instance = new GameObject("Singleto of" + typeof(T).ToString()).AddComponent<T>();//创建该类型组件对象，组件不能自行new
                    }
                }
                return instance;
            }
        }

        private void Awake()//缺点：由于在Awake方法中为静态属性赋值，所以调用者只能在Awake以后的脚本生命周期中访问
        {
            //如果当前组件在场景中默认存在，则通过as为字段赋值
            if (instance == null)
            {
                instance = this as T;//必须增加约束要求T是MonoSingleton<T>的子类
            }
        }
    }
}

